const tbody = document.querySelector('tbody');
// 省市区
const province = document.querySelector('select[name=province]');
const city = document.querySelector('select[name=city]');
const county = document.querySelector('select[name=county]');
// 表单
const form = document.querySelector('.add-form');
const addBtn = document.querySelector('.add-btn');
// 全局变量id
// let id
// 初始化渲染数据
async function getData() {
    const res = await axios({ url: '/student/list', })
    // console.log(res);
    const html = res.data.data.reduce((init, item) => {
        const { id, name, sex, age, group, province, city, county, salary, truesalary, phone } = item
        return init + `
      <tr>
        <th scope="row">${id}</th>
        <td>${name}</td>
        <td>${age}</td>
        <td>${sex}</td>
        <td>${group}组</td>
        <td>${phone}</td>
        <td>${salary}</td>
        <td>${truesalary}</td>
        <td>${province + city + county}</td>
        <td>
          <button type="button" class="btn btn-primary btn-sm editBtn" data-id="${id}">修改</button>
          <button type="button" class="btn btn-danger btn-sm deleteBtn" data-id=${id}>删除</button>
        </td>
      </tr> 
        `
    }, '')
    tbody.innerHTML = html
}
getData()

// 操作  省
async function getProvince() {
    getSeleteData('/geo/province', {}, province, '省')
}

getProvince()

// 给province绑定 change事件
province.addEventListener('change', e => {
    getSeleteData('/geo/city', { pname: province.value }, city, '市')
    county.innerHTML = county.firstChild.outerHTML;
})

// 给city绑定 change事件
city.addEventListener('change', e => {
    getSeleteData('/geo/county', { pname: province.value, cname: city.value }, county, '县')
})

//封装省市区函数
async function getSeleteData(url, params, target, targetName) {
    const res = await axios({
        url,
        params
    })
    const html = res.data.reduce((init, item) => {
        return init + `
        <option value=${item}>${item}</option>
        `
    }, `<option value=''>--${targetName}--</option>`)
    target.innerHTML = html
}

// 添加学生
form.addEventListener('submit', function (e) {
    e.preventDefault();
    // 用form-serialize
    const data = serialize(form, { hash: true, empty: true })

    const title = document.querySelector('#addModalLabel');
    if (title.innerText === "录入新学员") {
        // 删除data中的id属性
        delete data.id
    }
    // console.log(data);
    // 判断data的所有属性是否为空
    for (const key in data) {
        if (!data[key]) {
            toastr.error('请输入内容', '提示')
        }
        break;
    }
    // 调用
    setStudents(data)

})
// 封装
async function setStudents(data) {
    // 添加data里的学生信息到数据库
    const title = document.querySelector('#addModalLabel');
    let res
    if (title.innerText === "录入新学员") {
        // 删除data中的id属性
        res = await axios({
            url: '/student/add',
            method: 'post',
            data
        })
    } else if (title.innerText === "修改学生信息") {
        // data.id = id
        res = await axios({
            url: '/student/update',
            method: 'put',
            data
        })
    }
    getData()
    if (res.data.code === 0) {
        toastr.success(res.data.message, '恭喜')
    }
    $("#addModal").modal("hide");
    form.reset();       //  清空表单
    // 市县需要手动清空
    //  city.firstChild为DOM元素  outerHTML可以将DOM元素转化为自身的标签
    city.innerHTML = city.firstChild.outerHTML;
    county.innerHTML = county.firstChild.outerHTML;
}

//点击添加学生按钮
addBtn.addEventListener('click', function (e) {
    $('#addModal').modal('show')
    document.querySelector('#addModalLabel').innerHTML = '录入新学员';
})

// 点击修改学生按钮  事件委托
tbody.addEventListener('click', async function (e) {
    const target = e.target
    if (target.classList.contains('editBtn')) {
        $('#addModal').modal('show')
        document.querySelector('#addModalLabel').innerHTML = '修改学生信息';
        // 获取学生身上的id
        const id = target.dataset.id
        // 根据id请求数据
        const res = await axios({
            url: '/student/one',
            params: {
                id
            }
        })
        const obj = res.data.data
        // 初始化市县
        await getSeleteData('/geo/city', { pname: obj.province }, city, '市')
        await getSeleteData('/geo/county', { pname: obj.province, cname: obj.city }, county, '县')
        // 对象 ① 点调用  ② []调用
        for (const key in obj) {
            const formEle = document.querySelector(`[name=${key}]`)
            if (formEle && key !== "sex") {
                formEle.value = obj[key];
            }
        }
        document.querySelector(`[name=sex][value=${obj.sex}]`).checked = true;
    }
    // 删除
    if (target.classList.contains('deleteBtn')) {
        const id = target.dataset.id
        if (confirm('你确定删除吗？')) {
            const res = await axios({
                url: '/student/delete',
                method: 'delete',
                params: {
                    id
                }
            })
            if (res.data.code === 0) {
                toastr.success('删除成功！！！', '恭喜')
            }
        }
        getData();
    }
})
